<template>
  <div class="cmt">
    <h3>发表评论</h3>
    <textarea maxlength="120" placeholder="请输入要bb的内容（最多bb120个字）" v-model="msg"></textarea>
    <cube-button :light="true" @click="getmypl">发表评论</cube-button>
    <div class="cmt_main" v-for="(item, i) in comments" :key="item.add_time">
      <div class="cmt_head">第{{i+1}}楼 用户：{{item.user_name}} 发表时间：{{item.add_time | dataFormat}}</div>
      <div class="cmt_content">{{item.content==""? "此用户什么都没说，所以卡黄szd":item.content}}</div>
    </div>
    <cube-button :primary="true" @click="getmore">加载更多</cube-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      comments: [],
      pageIndex: 1,
      msg:""
    };
  },
  watch: {
    //加入监听是因为父组件和子组件同时发起异步请求不知道哪个先执行完，所以artid是个不定的值，于是等父组件先执行完再执行子组件的异步操作
      artid:function(){
        this.getcomments();
      }
  },
  methods: {
    getcomments() {
      this.$axios({
        method: "get",
        url:
          "http://www.liulongbin.top:3005/api/getcomments/" +
          this.artid +
          "?pageindex=" +
          this.pageIndex
      })
        .then(response => {
            console.log(this.artid);
            console.log(response);
          if (response.data.status == 0) {
            this.comments = this.comments.concat(response.data.message);
          }else{
              this.showToastTime("数据错误");
          }
        })
        .catch(err => {
          if (err) {
            this.showToastTime("服务器错误");
          }
        });
    },
    showToastTime(msg) {
      const toast = this.$createToast({
        time: 3000,
        txt: msg
      });
      toast.show();
    },
    getmore(){
        this.pageIndex++;
        this.getcomments();
    },
    getmypl(){
      if(this.msg.trim()==0){
        return this.showToastTime("评论为空")
      }else{
        this.$axios({
          method:"post",
          url:"http://www.liulongbin.top:3005/api/postcomment/"+this.artid,
          data:{
            content:this.msg
          }
        })
        .then(response=>{
          if(response.data.status==0){
            this.showToastTime(response.data.message);
            this.msg="";
          }else{
            this.showToastTime("数据获取失败")
          }
        })
        .catch(err=>{
          if(err){
            this.showToastTime("请求发起失败");
          }
        })
        // console.log(this.$route,this.artid);
      }
    }
  },
  props: ["artid"]
};
</script>

<style lang="less">
.cmt {
  h3 {
    margin-top: 10px;
    font-size: 20px;
  }
  textarea {
    margin-top: 10px;
    font-size: 15px;
  }
  .cmt_main {
    .cmt_head {
      margin-top: 20px;
      width: 100%;
      height: 20px;
      background: gray;
      font-size: 15px;
      text-align: center;
      line-height: 20px;
    }
    .cmt_content {
      margin-top: 5px;
      font-size: 25px;
      color: orange;
      width: 100%;
    //   height: 90px;
      text-align: center;
    //   line-height: 30px;
      margin-bottom: 5px;
    }
  }
}
</style>